package com.android.functionmanagement.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.functionmanagement.ControlCenter;
import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.receiver.AlarmReceiver;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * 获取手机信息
 */
public class DeviceUtils {
	public static int displayWidth = 0;
	public static int displayHeight = 0;
	public static float displaydensity = 0;
	public static int displayDpi = 0;

	/**
	 * 返回屏幕分辨率的宽度 px
	 * 
	 * @param act
	 * @return
	 */
	public static int getDisplayWidth(Context act) {
		if (displayWidth == 0) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) act).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			displayWidth = dm.widthPixels;
		}
		return displayWidth;
	}

	/**
	 * 返回屏幕分辨率的高度 px
	 * 
	 * @param act
	 * @return
	 */
	public static int getDisplayHeight(Context act) {
		if (displayHeight == 0) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) act).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			displayHeight = dm.heightPixels;
		}
		return displayHeight;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(float dpValue, Context act) {
		if (displaydensity == 0) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) act).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			displaydensity = dm.density;
		}
		return (int) (dpValue * displaydensity + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(float pxValue, Context act) {
		if (displaydensity == 0) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) act).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			displaydensity = dm.density;
		}
		return (int) (pxValue / displaydensity + 0.5f);
	}

	public static String getIMEI(Context context) {
		TelephonyManager telManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = telManager.getDeviceId(); // 手机上的IMEI号
		if (deviceId == null || "".equals(deviceId)) {
			return "";
		} else {
			return deviceId;
		}
	}

	public static String getNumber(Context context) {
		TelephonyManager telManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String num = telManager.getLine1Number(); // 手机上的sim号码
		if (num == null || "".equals(num)) {
			return "";
		} else {
			return num;
		}
	}
	
	/**
	 * 方法功能说明 ：判断当前网络状态是否可用
	 * 
	 * @param
	 * @return void
	 */
	public static boolean haveInternet(Context context) {
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conManager.getActiveNetworkInfo();
		if (info == null || !info.isConnected()) {
			return false;
		}
		// 漫游状态
		if (info.isRoaming()) {
			return true;
		}
		return true;
	}

	/**
	 * setAlarm:闹钟设置
	 * 
	 * @param action
	 *            操作
	 * @param requestCode
	 *            请求标识
	 * @param interval
	 *            重发间隔
	 * 
	 */
	public static void setAlarm(Context context, int action, int requestCode,
			int interval) {
		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmReceiver.class);
		intent.putExtra(ConstantGloble.ALARMACTION, action);
		if (Build.VERSION.SDK_INT >= 19) {
			PendingIntent alarmPendIntent = PendingIntent.getBroadcast(context,
					requestCode, intent, 0);
			if (alarmPendIntent != null)
				alarmMgr.cancel(alarmPendIntent);
			alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
					SystemClock.elapsedRealtime() + interval, alarmPendIntent);
		} else {
			PendingIntent alarmPendIntent = PendingIntent.getBroadcast(context,
					requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			if (alarmPendIntent != null)
				alarmMgr.cancel(alarmPendIntent);
			alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
					System.currentTimeMillis() + interval, interval,
					alarmPendIntent);
		}
	}

	/**
	 * cancelAlarm:取消闹钟
	 * 
	 * @param action
	 *            操作
	 * @param requestCode
	 *            请求标识
	 * @param interval
	 *            重发间隔
	 * 
	 */
	public static void cancelAlarm(Context context, int action, int requestCode) {
		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmReceiver.class);
		intent.putExtra(ConstantGloble.ALARMACTION, action);
		if (Build.VERSION.SDK_INT >= 19) {
			PendingIntent alarmPendIntent = PendingIntent.getBroadcast(context,
					requestCode, intent, 0);
			if (alarmPendIntent != null)
				alarmMgr.cancel(alarmPendIntent);
		} else {
			PendingIntent alarmPendIntent = PendingIntent.getBroadcast(context,
					requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			if (alarmPendIntent != null)
				alarmMgr.cancel(alarmPendIntent);
		}
	}

	/**
	 * 格式化日期
	 * @param time
	 * @return
	 */
	public static String formatDate(Date time,String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		String ctime = formatter.format(time);
		return ctime;
	}
	/**
	 * 获取VersionCode
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context)// 获取版本号(内部识别号)
	{
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	/**
	 * 将hashmap的值保存在SharedPreferences里面
	 * @param data
	 * @param context
	 */
	public static void saveSp(HashMap<String, Object> data,Context context){
		Iterator iter = data.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = entry.getKey().toString();
			Object val = entry.getValue();
			/*if(val instanceof String){
				SharedPreferencesUtils.setParam(context, key, val);
			}else if(val instanceof HashMap){
				saveSp((HashMap<String, Object>)val, context);
			}else if(val instanceof List){
				List list = (List) val;
				for (Object object : list) {
					if(object instanceof HashMap){
						saveSp((HashMap<String, Object>)object, context);
					}
				}
			}*/
			SharedPreferencesUtils.setParam(context, key, val.toString());
		}
	}
	
	/**
	 * 将hashmap的值保存在SharedPreferences里面
	 * @param data
	 * @param context
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void saveUserSp(HashMap<String, Object> data, Context context) {
		Iterator iter = ((HashMap<String, Object>) data.get("userBaseInfoBean"))
				.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = entry.getKey().toString();
			Object val = entry.getValue();
			SharedPreferencesUtils.setParam(context, key, val.toString());
		}
	}
	
	
	/**
	 * 获取请求头报文
	 * @param functionId
	 * @return
	 */
	public static HashMap<String, String> getreqHeadContent(String functionId,Context context){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(ConstantGloble.TERMINALTYPE, "2");
		map.put(ConstantGloble.TERMINALID, DeviceUtils.getIMEI(context));
		map.put(ConstantGloble.FUNCTIONID, functionId);
		map.put(ConstantGloble.TRANSTIME, DeviceUtils.formatDate(new Date(),"yyyyMMddhhmmss"));
		map.put(ConstantGloble.VERSION, DeviceUtils.getVersionCode(context)+"");
		return map;
	}
	/**
	 * 添加联系人
	 * @param context
	 * @param name
	 * @param phone
	 * @return
	 */
	public static Uri insertContact(Context context, String name, String phone) {
		ContentValues values = new ContentValues();
		values.put(People.NAME, name);
		Uri uri = context.getContentResolver().insert(People.CONTENT_URI,
				values);
		Uri numberUri = Uri.withAppendedPath(uri,
				People.Phones.CONTENT_DIRECTORY);
		values.clear();

		values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);
		values.put(People.NUMBER, phone);
		context.getContentResolver().insert(numberUri, values);
		return uri;
	}
	
	public static boolean haveContact(String content,Context context){
        Uri personUri = null;
        String columnName = null;
        personUri = Uri.parse("content://com.android.contacts/contacts");//new Uri("content://com.android.contacts/contacts");
		columnName = "display_name";
		String tmpNum = new String();// 记录临时号码
		// 处理联系人和邮件
		Cursor c = context.getContentResolver().query(personUri, null,
				columnName + " like \'%" + content + "%\'", null, null);// 查询所有包含content的名字
		// 获取联系人姓名
		try {
			for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
				int iNameIndex = c.getColumnIndex(columnName);
				String stringName = c.getString(iNameIndex);
				if (content.equals(stringName)) {
					return true;
				}
			}
		} catch (Exception e) {
		} finally {
			if (c != null) {
				c.close();
				c = null;
			}
		}
        return false;
	}
	
	/**
	 * 上传数据
	 */
	public static void uploadData(Context context, int type, int posType){
		HashMap<String, Object> copyFrom = new HashMap<String, Object>();
		copyFrom.put(ConstantGloble.REQHEAD, getreqHeadContent(ConstantGloble.W003, context));
		copyFrom.put(ConstantGloble.BODY, new UploadData(context, type, posType));
		JSONObject jsonObject = new JSONObject(copyFrom);
		ControlCenter.getInstanse().requestHttp(ConstantGloble.getBaseUri(context), "post", jsonObject, null, null, null, context);
	}
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	public static final boolean isGpsEnable(Context context) {
		int mode = Settings.Secure.getInt(context.getContentResolver(),
				Settings.Secure.LOCATION_MODE,
				Settings.Secure.LOCATION_MODE_OFF);
		return mode != Settings.Secure.LOCATION_MODE_OFF;
	}

	/**
	 * 
	 * @param context
	 */
	public static final void toggleGPS(Context context,boolean enable) {
		if(isGpsEnable(context) == enable){
			return;
		}
		if (enable)
			Settings.Secure.putInt(context.getContentResolver(),
					Settings.Secure.LOCATION_MODE,
					Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
		else
			Settings.Secure.putInt(context.getContentResolver(),
					Settings.Secure.LOCATION_MODE,
					Settings.Secure.LOCATION_MODE_OFF);
	}

	/**
	 * @param context
	 * @return
	 */
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

}
